package com.scarecrow.compack.component.movement {
	
	import com.scarecrow.compack.component.spatial.SpatialComponent
	import com.scarecrow.olga.core.timer.GameTimer;
	import com.scarecrow.olga.game.component.GameComponent;
	import com.scarecrow.olga.game.component.UpdateableComponent;
	import com.scarecrow.olga.game.object.event.GameObjectEvent;
	import flash.events.Event;
	
	/**
	 * ...
	 * @author Santiago.J.Elizalde
	 */
	public class SimpleMover extends UpdateableComponent {
		
		public static const X_VELOCITY:String = "vX";
		public static const Y_VELOCITY:String = "vY";
		public static const MAX_VELOCITY:String =  "vMax";
		
		protected var spatial:SpatialComponent;
		
		protected var maxVel:Number=0;
		private var xVel:Number=0;
		private var yVel:Number=0;
		
		public function SimpleMover(maxSpeed:Number) {
			maxVel = maxSpeed;
		}
		
		override protected function initialize():void {
			owner.setProp(X_VELOCITY, xVel);
			owner.setProp(X_VELOCITY, yVel);
			owner.setProp(MAX_VELOCITY, maxVel);
			if (owner.hasComponent(SpatialComponent)) {
				spatial = owner.getComponent(SpatialComponent) as SpatialComponent;
			} else {
				owner.addEventListener(GameObjectEvent.COMPONENT_ADDED, onComponentAdded);
			}
		}
		
		protected function onComponentAdded(e:GameObjectEvent):void {
			if (e.affectedComponent is SpatialComponent) {
				spatial = owner.getComponent(SpatialComponent) as SpatialComponent;
				owner.removeEventListener(GameObjectEvent.COMPONENT_ADDED, onComponentAdded);
			}
		}
		
		override public function update(ms:uint = 0):void {
			if (spatial) {
				spatial.x += xVel;
				spatial.y += yVel;
			}
		}
		override protected function releaseGameObject():void {
			this.enabled = false;
			this.spatial = null;
		}
		
		/**
		 * Object's movement speed in the X axis, in pixels per frame.
		 */
		public function get vX():Number {
			return xVel;
		}
		
		public function set vX(value:Number):void {
			xVel = value;
			owner.setProp(X_VELOCITY, value);
		}
		
		/**
		 * Object's movement speed in the Y axis, in pixels per frame.
		 */
		public function get vY():Number {
			return yVel;
		}
		
		public function set vY(value:Number):void {
			yVel = value;
			owner.setProp(Y_VELOCITY, value);
		}
	}
}